import time

from django.contrib import admin
from django.utils.safestring import mark_safe

# Register your models here.
from django.urls import reverse
from django.utils.html import format_html

from article_app.models import Article
from user_app.models import User
from utils.encode_decode import bw_encode


@admin.register(Article)
class ArticleAdmin(admin.ModelAdmin):
    list_display = ('title', 'author', 'pub_time', 'my_is_delete', 'my_is_valid', 'content_text')
    fields = ('title', 'is_delete', 'is_check')

    list_display_links = ['title']
    list_filter = ['title']
    search_filter = ['title', 'pub_time']
    actions = ['delete_item']
    # list_per_page设置每页显示多少条记录，默认是100条
    list_per_page = 50
    # ordering设置默认排序字段，负号表示降序排序
    ordering = ('-add_time',)
    # list_editable 设置默认可编辑字段
    list_editable = []
    actions_on_top = True
    actions_on_bottom = True
    save_on_top = False

    def delete_item(modeladmin, request, queryset):
        for i in queryset:
            i.delete()
        return modeladmin.message_user(request, f'成功删除{len(queryset)}条记录')

    delete_item.short_description = '删除已选项'

    def save_model(self, request, obj, form, change):
        # obj.password = bw_encode(obj.password)  # 修改密码值为hex
        return super().save_model(request, obj, form, change)

    @staticmethod
    def get_add_time(time_):
        time_array = time.localtime(time_)  # 转换为可用的时间，就是下面的%Y %m %d
        day_time = time.strftime('%Y-%m-%d %H:%M:%S', time_array)  # 取上面的timeArray中的对应值0
        return day_time

    @mark_safe
    def my_is_delete(self, obj):
        """自定义列表字段"""
        ret = "已删除" if obj.is_delete else "正常"
        return ret

    my_is_delete.short_description = '是否删除'

    def my_is_valid(self, obj):
        """自定义列表字段"""
        ret = "不允许" if not obj.is_check else "允许"
        return ret

    my_is_valid.short_description = '是否允许发表'

    def pub_time(self, obj):
        """自定义列表字段"""
        ret = self.get_add_time(obj.add_time)
        return ret

    pub_time.short_description = '发布时间'

    def author(self, obj):
        """自定义列表字段"""
        ret = obj.u_id.nick_name
        return ret

    author.short_description = '作者'



